<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

use think\Db;

/**
 * 会员模型
 */
class Member extends ModelBase
{
    protected $insert = ['create_time','invite_code'];


    /**
     * 连用户表
     */
    public function mem(){
        return $this->belongsTo('Member','leader_id','id');
    }

    /**
     * 关联账户表
     */
    public function account(){
        return $this->hasMany('UserAccount','user_id','id');
    }


    /**
     * 关联法币账户表
     */
    public function ethaccount(){
        return $this->hasOne('EthAccount','user_id','id');
    }
    /**
     * 店铺账户
     */
    public function shopaccount($wallet_id,$key=''){
          $info=OtcShop::where(['user_id'=>$this->id,'wallet_id'=>$wallet_id,'state'=>2])->find();
          if($info){
              if($key){
                  return $info[$key];
              }else{
                  return $info;
              }
          }
        return format_money(0,8);
    }

    /**
     * 赌王账户
     */
    public function kingaccount($key=''){
        $info=GamblerKing::where(['user_id'=>$this->id,'state'=>2])->find();
        if($info){
            if($key){
                return $info[$key];
            }else{
                return $info;
            }
        }
        return format_money(0,8);
    }


    /**
     * 关联等级表
     */
    public function level(){
        return $this->belongsTo('UserLevel','level_id','id');
    }

    /**
     * 获取总下注
     */

    public function get_total_money($where){
        $where['user_id']=$this->id;
        $where['user_investment_id']=0;
        return  BetsLog::where($where)->sum('number')+0;
    }

    /**
     * 获取总盈利
     */

    public function get_profit_bet($where){
        $where['user_id']=$this->id;
        $where['user_investment_id']=0;
        $where['number']=['gt',0];
        return  BetsLog::where($where)->sum('number')+0;
    }

    /**
     * 获取常驻地址
     */

    public function getAlwaysAddressAttr(){

        return  UserLoginAddress::where(['user_id'=>$this->id])->order('count desc')->value('city');
    }

    /**
     * 获取最新登录记录
     */

    public function getLoginLogAttr(){

        return  LoginLog::where(['user_id'=>$this->id])->order('id desc')->find();
    }

    /**
     * 获取相同ip数量
     */

    public function getIpSameAttr(){

        return  self::where(['reg_ip'=>$this->reg_ip])->count();
    }


    /**
     * 获取最新登录记录
     */

    public function getUuidSameAttr(){

        return  self::where(['uuid'=>$this->uuid])->count();
    }

    /**
     * 获取总亏损
     */

    public function get_loss_bet($where){
        $where['user_id']=$this->id;
        $where['user_investment_id']=0;
        $where['number']=['lt',0];
        return  BetsLog::where($where)->sum('number')+0;
    }


    /**
     * 迎面率
     */
    public function getWinnRateAttr(){
        if($this->profit_bet==0 ||  $this->total_money==0  || $this->loss_bet==0 ){
            return 0;
        }
        return  format_money(($this->profit_bet-$this->loss_bet)/$this->total_money*100,2);
    }
    /**
     * 推荐人用户名
     */
    public function getLeaderNicknameAttr(){
        if($this->leader_id){
            return $this->mem->username;
        }else{
            return '-------';
        }
    }


    /**
     * 用户是否导入钱包
     */
    public function getIsExcelWalletAttr(){
        if(CoinUsersAddress::get(['userid'=>$this->id])){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 密码修改器
     */
    public function setPasswordAttr($value)
    {
        
        return data_md5_key($value);
    }

    /**
     * 自动完成邀请码
     */
    public function setInviteCodeAttr()
    {

        return create_invite_code();
    }

    /**
     * 获取总金额
     */
    public function getTotalMoneyAttr(){
        $money=0;
        $wallet=Wallet::where('1=1')->column('parities','id');
        $wallet_account=UserAccount::all(['user_id'=>$this->id]);
        foreach ($wallet_account as $k=>$v){
            if($v['balance']>0){
                $money+=$v['balance']*($wallet[$v['wallet_id']]-getConfig('eth_reduce_price'));
            }

        }
        $eth_account=EthAccount::get(['user_id'=>$this->id]);
        if($eth_account['usdt_do']){
            $money+=$eth_account['usdt_do']*($wallet[8]-getConfig('eth_reduce_price'));
        }
        if($eth_account['eth_do']){
            $money+=$eth_account['eth_do']*($wallet[6]-getConfig('eth_reduce_price'));
        }
        if($eth_account['btc_do']){
            $money+=$eth_account['btc_do']*($wallet[7]-getConfig('eth_reduce_price'));
        }
        return $money;
    }

    /**
     * 头像
     */
    public function getAvtarAttr()
    {
        $id=$this->cover_id;
        $info = Db::name('picture')->where(['id' => $id])->field('path,url')->find();

        if (!empty($info['url'])) {

            return $info['url'];
        }


        if (!empty($info['path'])) {

            return DMOAIN_URL .'/'. 'upload/picture/'.$info['path'];
        }

        return '';

    }

    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr($value)
    {

        return TIME_NOW;
    }

    /**
     * 自动获取钱包
     */
    public function wallet(){
        return  $this->account()->where(['wallet_id'=>['in',[1,3]],'user_id'=>$this->id])->select();
    }

    /**
     * 自动获取钱包
     */
    public function block_wallet($id){
        return  $this->account()->where(['wallet_id'=>$id,'user_id'=>$this->id])->order('wallet_id asc' )->find();
    }
    /**
     * 会员树
     */

    public function  member_tree($id){
        $trees = array();
        $member=self::get($id);
        $trees['name'] = $this->getTreeBaseInfo($id);
        if(!$member['ceng_member']){
            return $trees;
        }else{
            $ids=explode(',',$member['ceng_member']);
        }

        foreach ( $ids as $k=>$v){
            $arr[] =$this->member_tree($v);

            $trees['children']=$arr;

        }
        return $trees;
    }

    //隐藏中间四位
    public function getNewMobileAttr(){
        if($this->mobile){
           return yc_phone($this->mobile);

        }else{
            return '';
        }


    }




    public function getDailyBonusAttr(){
        $date=date('Y-m-d');
        $start_time=strtotime($date.' 00:00:00');
        $end_time=strtotime($date.' 23:59:59');
        $where['create_time']=['between',[$start_time,$end_time]];
        $where['user_id']=$this->id;
        $where['is_reward']=1;
        $sum=UserAccountLog::where($where)->sum('number');
        $sum=$sum?$sum:0;
        return $sum;
    }

    public function getPrevLoginIpAttr(){
        $list=LoginLog::where(['user_id'=>$this->id])->order('id desc')->limit(2)->select();
        if(!empty($list[1])){
            return $list[1]['ip'];
        }
        return '';
    }

    public function getPrevLoginAreaAttr(){
       $list=LoginLog::where(['user_id'=>$this->id])->order('id desc')->limit(2)->select();
       if(!empty($list[1])){
           return $list[1]['location'];
       }
       return '';
    }
    //验证支付密码
    public function check_pin_password($password){

        //加密密码
        if(md5($password.'pin')!= $this->pin_password){
            return false;
        }


        return true;
    }

    //赌王委托输
    public function  getInvestmentLoseAttr(){

        $money=Db::name('investment_bet_log')->where(['type'=>1,'state'=>['gt',1],'profit'=>['lt',0],'user_id'=>$this->id])->sum('profit')+0;
        return  -$money;




    }
    //赌王委托赢
    public function  getInvestmentWinAttr(){

        $money=Db::name('investment_bet_log')->where(['type'=>1,'state'=>3,'profit'=>['gt',0],'user_id'=>$this->id])->sum('profit')+0;
        return  -$money;

    }

    /***
     * 用户总下注数量
     */

    public function getBetsTotalAttr(){
        $money=0;
        $money+=Db::name('investment_bet_log')->where(['user_id'=>$this->id])->sum('number')+0;
        $money+=GamesLog::where(['type'=>4,'user_id'=>$this->id,'entrust_count'=>0])->sum('number');

        return $money;
    }


    //用户输
    public function  getUserLoseAttr(){


        $money=GamesLog::where(['type'=>4,'user_id'=>$this->id,'entrust_count'=>0,'is_winner'=>2])->sum('profit')+0;
        $money+=Db::name('investment_bet_log')->where(['type'=>2,'user_id'=>$this->id,'profit'=>['gt',0],'state'=>['gt',1]])->sum('profit');
        return  -$money;


    }
    //用户赢
    public function  getUserWinAttr(){

        $money=GamesLog::where(['type'=>4,'user_id'=>$this->id,'entrust_count'=>0,'is_winner'=>1,'state'=>4])->sum('profit')+0;
        $money+=Db::name('investment_bet_log')->where(['type'=>2,'user_id'=>$this->id,'profit'=>['gt',0],'state'=>['gt',1]])->sum('profit');
        return  $money;


    }

    public function  getrecharge($where){

        $where['type']=4;
        $where['state']=1;
        $sum=Transfer::where($where)->sum('money');
        $sum=$sum?$sum:0;
        return $sum;
    }

    //盈利总额
    public function  getprofit($where){

        $where['type']=11;
        $sum=UserAccountLog::where($where)->sum('number');
        $sum=$sum?$sum:0;

        return $sum;
    }

    //可调最大值
    public function  getMaxGamePointAttr($where){

       $leader=Self::get($this->leader_id);
       if($leader){
           return $leader['game_point_money'];
       }else{
          return getConfig('max_point') ;
       }


    }
    //可调最小值
    public function  getMinGamePointAttr($where){

        $leader=Self::get($this->leader_id);
        if($leader){
            return $leader['game_point_money']*(100-getConfig('set_point'))/100;
        }else{
            return getConfig('max_point')*(100-getConfig('set_point'))/100 ;
        }
    }


    public function getChildrenCountAttr(){
        if($this->ceng_member){
            return count(explode(',',$this->ceng_member));
        }else{
            return 0;
        }

    }

    public function getSanCountAttr(){
        return self::where(['path'=>['like',['%,'.$this->id.',%']]])->count();

    }

    private function getTreeBaseInfo($id)
    {
        $member=self::get($id);
        $member->is_king==1?$king_is='是':$king_is='否';
        return '会员账号:   '.$member['username'].'  [ 手机号码: '.$member['mobile'].'   会员等级:  '.$member->level->level_name.'  直推人数:  '.$member->children_count.'  团队总人数:  '.$member->san_count.'人   是否赌王:   '.$king_is.' ]';
    }




    /***
     * 业绩升级
     */

    public  function   upgrade($money){
        //  所有上级增加业绩
        if($money){
            $path=$this->path;
            if($path){
                $ids=explode(',',substr($path,0,-1));
                array_shift($ids);
                //团队业绩增加
                self::where(['id'=>['in',$ids]])->setInc('achievement',$money);
                if($this->leader_id){
                    //直推业绩增加
                    self::where(['id'=>$this->leader_id])->setInc('share_achievement',$money);
                }

            }
        }

    }

//
//    /***
//     * 业绩降级
//     */
//
    public  function   downgrade($money){
        //  所有上级减少业绩
        $path=$this->path;

        if($path){
            $ids=explode(',',substr($path,0,-1));
            array_shift($ids);
           // dd($ids);
            //团队业绩减少
            self::where(['id'=>['in',$ids]])->setDec('achievement',$money);
            if($this->leader_id){
                //直推业绩减少
                self::where(['id'=>$this->leader_id])->setDec('share_achievement',$money);
            }
//            $this->downgrade_level($this->leader_id);

        }else{
            $this->downgrade_level($this->leader_id);
        }
    }



    /***
     * 升级
     */
    public function  upgrade_level($ids){
//        dd($list);
            $user_ids=$level_logs=[];
            foreach ($ids as $k=>$v){
                $member=self::get($v);
                if($member->level_id>1){
                    $level=UserLevel::get( ($member->level_id+1));
                    if($level){
                        $leader_ids=explode(',',$member['ceng_member']);
                        //直推有效人数
                        
                        // $share_same_count=UserKingInvestment::where(['create_time'=>['between',[ (getTodayStart()-86400*3),TIME_NOW]],'user_id'=>['in',$leader_ids],'state'=>['in',[4,5,6,7,8]]])->group('user_id')->count();
                        $share_same_count=Member::where(['id'=>['in',$leader_ids],'level_id'=>['gt',1]])->count();
                        $share_team_count=$member['san_count'];
                        if( $share_same_count>=$level['share_number'] && $share_team_count>=$level['team_number']){

                            $user_ids[$v]=[
                                'level_id'=>1
                            ];
                            //写入升级记录
                            $level_log=[
                                'type'=>1,
                                'user_id'=>$member['id'],
                                'level'=>$level['id'],
                                'create_time'=> TIME_NOW
                            ];
                            $level_logs[]=$level_log;
                            $notice= [
                                'title'=>'您的账户，在'.date('Y-m-d H:i:s').'时间，升级为'.$level->level_name.'级别，恭喜您！您的社区越来越强大',
                                'user_id'=>$member['id'],
                                'content'=>'您的账户，在'.date('Y-m-d H:i:s').'时间，升级为'.$level->level_name.'级别，恭喜您！您的社区越来越强大',
                                'type'=>1,
                                'create_time'=>TIME_NOW
                            ];
                            $notices[]=$notice;
                        }
                    }
                }
            }

            if(!empty($user_ids)){
                $sql4 = updateAllSql("tp_member",key($user_ids),$user_ids,"id");
                Db::execute($sql4);
                UserLevelLog::insertAll($level_logs);
                UserNotice::insertAll($notices);
            }


    }


    /***
     * 降级
     */
    public function downgrade_level($ids){
        $user_ids=$level_logs=[];
        foreach ($ids as $k=>$v){

            $member=self::get($v);
            if($member->level_id>3 ){
                $level=UserLevel::get($member->level_id);
                if($level){
                    $leader_ids=explode(',',$member['ceng_member']);

                    if($leader_ids){
                        //直推有效人数
                        if($leader_ids){
                            $share_same_count=UserKingInvestment::where(['create_time'=>['between',[(getTodayStart()-86400*3),TIME_NOW]],'user_id'=>['in',$leader_ids],'state'=>['in',[4,5,6,7,8]]])->group('user_id')->count();
                        }else{
                            $share_same_count=0;
                        }

                        if( $share_same_count<$level['share_number']){

                            $user_ids[$v]=[
                                'level_id'=>-1
                            ];
                            //写入升级记录
                            $level_log=[
                                'type'=>2,
                                'user_id'=>$member['id'],
                                'level'=>$level['id']-1,
                                'create_time'=> TIME_NOW
                            ];
                            $level_logs[]=$level_log;
                            $notice= [
                                'title'=>'您的账户，3天一周期的考核不通过，已为为您降级，本次考核的直推人数为'.$level['share_number'].'人，实际有效直推人数为'.$share_same_count.'人。',
                                'user_id'=>$member['id'],
                                'content'=>'您的账户，3天一周期的考核不通过，已为为您降级，本次考核的直推人数为'.$level['share_number'].'人，实际有效直推人数为'.$share_same_count.'人。',
                                'type'=>1,
                                'create_time'=>TIME_NOW
                            ];
                            $notices[]=$notice;
                        }
                    }

                }
            }
        }

        if(!empty($user_ids)){
            $sql4 = updateAllSql("tp_member",key($user_ids),$user_ids,"id");
            Db::execute($sql4);
            UserLevelLog::insertAll($level_logs);
            UserNotice::insertAll($notices);
        }

    }

    /***
     * 获取等级进度百分比
     */

    public function get_level_progress(){
        $level=UserLevel::get(($this->level_id+1));
        $leader_ids=explode(',',$this->ceng_member);
        if($leader_ids){
            $children_count=Member::where(['id'=>['in',$leader_ids],'level_id'=>['gt',1]])->count();
        }else{
            $children_count=0;
        }

        $progess=0;
        //当前直推人数
        $level_share_count=$level['share_number']-$children_count;
        if($level_share_count>0){
            $progess+=$children_count/$level['share_number']*50;
            $progess=format_money($progess,2);
        }else{
            $level_share_count=0;
            $progess+=50;
        }

        $level_team_count=$level['team_number']-$this->san_count;

        if($level_team_count>0){
            $progess+=$this->san_count/$level['team_number']*50;
            $progess=format_money($progess,2);
        }else{
            $level_team_count=0;
            $progess+=50;
        }

        return ['level_share_count'=>$level_share_count,'level_team_count'=>$level_team_count,'level_same_count'=>0,'level_achievement'=>0,'progess'=>$progess];
    }

}
